package com.ruijie.autotest.log.common.socket;

import com.minelx.util.socket.TCPPortService;
import com.ruijie.autotest.log.common.crypto.Crypto;
import com.ruijie.autotest.log.core.data.ITable;
import com.ruijie.autotest.log.impl.data.SimpleTable;
import com.ruijie.autotest.log.impl.parse.ICellsParser;
import com.ruijie.autotest.log.validation.hangzhoudewangxin.WIFILOGOUT.TableFactory;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;

import java.io.IOException;

public class TCPPortTableFactory implements TableFactory {

	private final SimpleTable.Builder tableBuilder;

	private final TCPPortService tcpPortService;

	private static final Logger logger = LoggerFactory.getLogger(TCPPortTableFactory.class);

	public TCPPortTableFactory(int port, SimpleTable.Builder tableBuilder, ICellsParser cellsParser, Crypto crypto) throws IOException {
		this.tableBuilder = tableBuilder;
		tcpPortService = new TCPPortService(port, received -> {
			logger.info(() -> "received...");
			byte[] decryptedBytes = crypto.doCrypto(received);
			logger.info(() -> "decrypted: " + new String(decryptedBytes));
			tableBuilder.addRow(cellsParser.parseCells(new String(decryptedBytes)));
		});
	}

	@Override
	public ITable createTable() {
		return tableBuilder.build();
	}

	public void start() {
		tcpPortService.start();
	}

	public void stop() {
		tcpPortService.stop();
	}
}
